package com.xinya.taobaosale.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.xinya.taobaosale.R;
import com.xinya.taobaosale.model.LoadState;
import com.xinya.taobaosale.model.domain.CategoryBean;
import com.xinya.taobaosale.model.domain.HomePagerDiscoveryBean;
import com.xinya.taobaosale.ui.activity.TicketActivity;
import com.xinya.taobaosale.ui.adapter.HomePageListAdapter;
import com.xinya.taobaosale.ui.adapter.HomePagerBannerAdapter;
import com.xinya.taobaosale.ui.presenter.impl.HomePagerPresenterImpl;
import com.xinya.taobaosale.ui.presenter.impl.TicketPresenterImpl;
import com.xinya.taobaosale.ui.presenter.interfaces.IHomePagerCallback;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: HomePagerFragment
 * @Description: java类作用描述
 * @Author: mhzhuxinya@163.com
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class HomePagerFragment extends BaseFragment implements IHomePagerCallback, OnLoadMoreListener {

    private static final String TAG = "HomePagerFragment";
    @BindView(R.id.home_pager_list_container)
    RecyclerView homePagerListContainer;
    Banner<HomePagerDiscoveryBean, HomePagerBannerAdapter> pagerBanner;
    TextView homePagerTitle;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    private int mMaterialId;
    private HomePageListAdapter mHomePageListAdapter;
    private HomePagerBannerAdapter mHomePagerBannerAdapter;

    public static HomePagerFragment newInstance(CategoryBean category) {
        Bundle args = new Bundle();
        args.putString("title", category.getTitle());
        args.putInt("id", category.getId());
        HomePagerFragment fragment = new HomePagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_pager_home;
    }

    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);

        View bannerView = LayoutInflater.from(getContext()).inflate(R.layout.head_home_pager_banner, (ViewGroup) rootView, false);
        pagerBanner = bannerView.findViewById(R.id.pager_banner);
        homePagerTitle = bannerView.findViewById(R.id.home_pager_title);

        homePagerListContainer.setLayoutManager(new LinearLayoutManager(getContext()));
        mHomePageListAdapter = new HomePageListAdapter(R.layout.item_home_page_list);
        mHomePageListAdapter.addHeaderView(bannerView);
        homePagerListContainer.setAdapter(mHomePageListAdapter);

        mHomePagerBannerAdapter = new HomePagerBannerAdapter(new ArrayList<>());

        pagerBanner.setAdapter(mHomePagerBannerAdapter)
                .setIndicator(new RectangleIndicator(getContext()))
                .setIndicatorNormalColorRes(R.color.colorWhite)
                .setIndicatorSelectedColorRes(R.color.colorTianMaoRed)
                .addBannerLifecycleObserver(getViewLifecycleOwner());

        // refresh
        smartRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        smartRefreshLayout.setHeaderHeight(0);
        smartRefreshLayout.setOnLoadMoreListener(this);
    }

    @Override
    protected void initData(View rootView) {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return;
        }
        String title = bundle.getString("title", "");
        mMaterialId = bundle.getInt("id", -1);

        // 设置标题
        homePagerTitle.setText(title);

        HomePagerPresenterImpl.INST.getHomePagerDiscoveryOrMore(mMaterialId);

        // list点击事件
        mHomePageListAdapter.setOnItemClickListener((adapter, view, position) -> {
            HomePagerDiscoveryBean bean = mHomePageListAdapter.getData().get(position);
            goToTicketActivity(bean);
        });

        // banner点击事件
        mHomePagerBannerAdapter.setOnBannerListener((data, position) -> {
            HomePagerDiscoveryBean bean = pagerBanner.getAdapter().getData(position);
            goToTicketActivity(bean);
        });
    }

    private void goToTicketActivity(HomePagerDiscoveryBean bean) {
        Log.d(TAG, "goToTicketActivity: " + bean.getTitle());
        TicketPresenterImpl.INST.onTicketLoaded(
                "https:" + bean.getCoupon_click_url(),
                bean.getTitle(),
                bean.getPict_url());
        Log.d(TAG, "goToTicketActivity: " + bean.getClick_url());
        startActivity(new Intent(getContext(), TicketActivity.class));
    }

    @Override
    protected void registerPresenter() {
        HomePagerPresenterImpl.INST.register(this);

    }

    @Override
    protected void unRegisterPresenter() {
        HomePagerPresenterImpl.INST.unRegister(this);
    }

    @Override
    public void onHomePagerDiscovery(int id, List<HomePagerDiscoveryBean> dataList) {
        if (id != mMaterialId) {
            return;
        }
        Log.d(TAG, "onHomePagerDiscovery: " + dataList.size());
        // listView更新
        mHomePageListAdapter.setNewInstance(dataList);
        // banner 没有具体接口,以dataList的最后4个作为banner数据
        if (dataList.size() <= 4) {
            return;
        }
        List<HomePagerDiscoveryBean> mBannerDataList = new ArrayList<>(dataList.subList(dataList.size() - 4, dataList.size()));
        pagerBanner.setDatas(mBannerDataList);

    }


    @Override
    public void onHomePagerDiscoveryOrMore(int id, List<HomePagerDiscoveryBean> dataList) {
        if (id != mMaterialId) {
            return;
        }
        Log.d(TAG, "onHomePagerDiscovery: " + id + " --> " + dataList.size());

        mHomePageListAdapter.addData(dataList);
        refreshFinish(true);
    }

    @Override
    public void onLoadSuccess(int id) {
        if (id != mMaterialId) {
            return;
        }
        switchLoadState(LoadState.SUCCESS);
    }

    @Override
    public void onLoadError(int id) {
        if (id != mMaterialId) {
            return;
        }
        switchLoadState(LoadState.ERROR);
    }

    @Override
    public void onLoadEmpty(int id) {
        if (id != mMaterialId) {
            return;
        }
        switchLoadState(LoadState.EMPTY);
    }

    @Override
    public void onLoading(int id) {
        if (id != mMaterialId) {
            return;
        }
        switchLoadState(LoadState.LOADING);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        Log.d(TAG, "onLoadMore: ");
        HomePagerPresenterImpl.INST.getHomePagerDiscoveryOrMore(mMaterialId);
    }

    private void refreshFinish(boolean flag) {
        if (flag) {
            smartRefreshLayout.finishLoadMore(100);
            return;
        }
        smartRefreshLayout.finishLoadMore(2000, false, false);
    }

}
